<template>
    <span>{{ displayValue }}</span>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';

const props = defineProps({
    value: {
        type: Number,
        required: true
    },
    duration: {
        type: Number,
        default: 1000
    }
});

const displayValue = ref(0);

const animate = (endValue) => {
    const startValue = displayValue.value;
    const startTime = Date.now();
    const duration = props.duration;

    const step = () => {
        const currentTime = Date.now();
        const progress = Math.min((currentTime - startTime) / duration, 1);

        // 使用缓动函数让动画更平滑
        const easeProgress = 1 - Math.pow(1 - progress, 3);
        displayValue.value = Math.round(startValue + (endValue - startValue) * easeProgress);

        if (progress < 1) {
            requestAnimationFrame(step);
        } else {
            displayValue.value = endValue;
        }
    };

    requestAnimationFrame(step);
};

watch(() => props.value, (newVal) => {
    animate(newVal);
});

onMounted(() => {
    animate(props.value);
});
</script>
